const path = require('path')

const Koa = require('koa')
const bobyParser = require('koa-bodyparser')
const cors = require('@koa/cors')
const Router = require('koa-router')
const static = require('koa-static')

const InitCore = require('./core/init')

const errorCatch = require('./middlewares/exceptionCatch')

const conf = require('./config/config')

const { jwt } = require('./core/jwt')

const { success, json } = require('./app/lib/helper')

const app = new Koa()

const router = new Router()

// 捕获全局错误
app.use(errorCatch)

// 挂载 jwt 到 app 上
jwt.initApp(app, conf.security.secret);

// 挂载 success 方法到 app 上
success(app)
// 挂载 json 方法到 app 上
json(app)

function indexPage(app) {
  router.get('/', async ctx => {
    ctx.type = 'html';
    ctx.body = 
    `
      <style type="text/css">
        *{ padding: 0; margin: 0; } 
        div{ padding: 4px 48px;} 
        a{color:#2E5CD5;cursor:pointer;text-decoration: none} 
        a:hover{text-decoration:underline; } 
        body{ background: #fff; font-family:"Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} 
        h1{ font-size: 100px; font-weight: normal;margin-bottom: 12px; } 
        p{ line-height: 1.6em; font-size: 42px }
      </style>
      <div style="padding: 24px 48px;">
        <p>
          Make Project Server <br/> <span style="font-size:30px">心上无垢，方得始终。</span>
        </p>
        <p style="font-size:20px">
          Api文档：
          <a target="_blank" href="/doc/">http://api.makeadmin.com/doc/</a>
        </p>
      </div> 
    `;
  });
}

indexPage(app)

// post 参数处理
app.use(bobyParser())

// 跨域配置
app.use(cors())

// 首页加载路由
app.use(router.routes())

// 静态资源配置
app.use(static(path.join(__dirname, './static')))

// 入口方法
InitCore.init(app)

// 监听端口 5000
app.listen(conf.port, () => {
  console.log(`listening at http://localhost:${conf.port}`);
})
